package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.common.exception.CustException;
import com.heima.common.message.PublishArticleConstants;
import com.heima.common.wemedia.WemediaConstants;
import com.heima.feigns.AdminFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Value("${file.oss.web-site}")
    private String webSite;

    @Autowired
    private WmNewsService wmNewsService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void autoScanWmNews(Integer id) {
        log.info("成功接收到文章自动审核消息 ==》 待审核文章id:{}",id);
        //1.根据id查询自媒体文章数据
        WmNews wmNews = wmNewsService.getById(id);
        if (wmNews == null){
            log.error("文章不存在，自动审核失败， 文章id:{}",id);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在，自动审核失败");
        }
        //2.判断文章的状态是否为 1 （防止重复消费）
        if (!WemediaConstants.WM_NEWS_SUMMIT_STATUS.equals(wmNews.getStatus())){
            log.error("当前文章待审核状态，无需审核  文章id:{}",id);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章待审核状态，无需审核");
        }
        //3.开始审核
        //3.1抽取出文章的所有文本内容和图片路径
        Map contentAndImages = parseContentAndImages(wmNews);
        //3.2 DFA自管理的敏感词审核 失败将状态改为 2
        boolean sensitiveScan = handleSensitive((String)contentAndImages.get("content"),wmNews);
        if (!sensitiveScan){
            log.info("当前文章有敏感词汇，审核未通过  文章id:{}",id);
            return;
        }
        //3.3阿里云内容安全文本审核 失败将状态改为 2
        boolean textScan = handleText((String)contentAndImages.get("content"),wmNews);
        if (!textScan){
            log.info("当前文章有违规信息，阿里云文本审核未通过  文章id:{}",id);
            return;
        }
        //3.4阿里云图片审核 失败将状态改为 2
        List<String> imagesList = (List<String>) contentAndImages.get("images");
        if (!CollectionUtils.isEmpty(imagesList)) {
            boolean imagesScan = handleImages(imagesList,wmNews);
            if (!imagesScan){
                log.info("当前文章图片内容有违规信息，阿里云图片安全审核未通过  文章id:{}",id);
                return;
            }
        }
        //4.如果全部审核通过，将文章状态改为8
        updateWmNews(wmNews,WmNews.Status.SUCCESS.getCode(), "审核通过");
        //5.根据文章的具体发布时间  发送延时发布消息
        //5.1计算延迟时间
        long publishTime = wmNews.getPublishTime().getTime(); //获取发布时间
        long nowTime = System.currentTimeMillis(); //获取当前系统时间
        long remainTime = publishTime - nowTime; //延时发布时间
        //5.2发送消息，并设置延迟时间
        rabbitTemplate.convertAndSend(
                PublishArticleConstants.DELAY_DIRECT_EXCHANGE,
                PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY,
                wmNews.getId(),
                new MessagePostProcessor() {
                    /**
                     * 消息的后置处理器，可以对消息属性进行设置
                     * @param message
                     * @return
                     * @throws AmqpException
                     */
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        //设置 x-delay 延迟时间
                        message.getMessageProperties().setHeader("x-delay",remainTime <= 0 ? 0 : remainTime);
                        return message;
                    }
                }
        );
        log.info("成功发送延时文章消息 文章id：{}  延时时间：{}",wmNews.getId(),remainTime);
    }

    private boolean handleImages(List<String> imagesList, WmNews wmNews) {
        boolean flag = false;
        //1.阿里云图片审核
        try {
            ScanResult scanResult = greenScan.imageUrlScan(imagesList);
            //2.判断suggestion的值修改状态 block：2  review：3  pass：true  null：3
            String suggestion = scanResult.getSuggestion();
            switch (suggestion){
                case "block" :
                    updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"文章中有违规信息" + scanResult.getLabel());
                    break;
                case "review" :
                    updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"文章中有不确定信息，为您转为人工审核");
                    break;
                case "pass" :
                    flag = true;
                    break;
                default:
                    updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"阿里云图片审核出现异常，为您改为人工审核");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云图片审核出现异常，为您改为人工审核");
            updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"阿里云图片审核出现异常，为您改为人工审核");
        }
        return flag;

    }

    @Autowired
    private GreenScan greenScan;

    private boolean handleText(String content, WmNews wmNews) {
        boolean flag = false;
        //1.阿里云文本审核
        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            //2.判断suggestion的值修改状态 block：2  review：3  pass：true  null：3
            String suggestion = scanResult.getSuggestion();
            switch (suggestion){
                case "block" :
                    updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"文章中有违规信息" + scanResult.getLabel());
                    break;
                case "review" :
                    updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"文章中有不确定信息，为您转为人工审核");
                    break;
                case "pass" :
                    flag = true;
                    break;
                default:
                    updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"阿里云自动文本审核出现异常，为您改为人工审核");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云自动文本审核出现异常，为您改为人工审核");
            updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"阿里云自动文本审核出现异常，为您改为人工审核");
        }
        return flag;
    }

    @Autowired
    private AdminFeign adminFeign;

    /**
     * DFA自管理的敏感词审核
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitive(String content, WmNews wmNews) {
        //1.使用feign远程调用查询敏感词列表方法
        ResponseResult<List<String>> sensitivesResult = adminFeign.sensitives();
        if (!sensitivesResult.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用出错，查询敏感词列表失败");
        }
        List<String> sensitives = sensitivesResult.getData();
        //2.基于DFA算法，封装数据模型，检测文本内容中是否包含敏感词
        SensitiveWordUtil.initMap(sensitives);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (!CollectionUtils.isEmpty(map)){
            //有敏感词 修改状态为 2
            updateWmNews(wmNews, WmNews.Status.FAIL.getCode(),"文本内容包含敏感词" + map);
            return false;
        }
        return true;
    }

    /**
     * 文章状态修改
     * @param wmNews 文章对象
     * @param status 文章状态
     * @param reason 失败原因
     */
    public void updateWmNews(WmNews wmNews, short status, String reason){
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsService.updateById(wmNews);
    }

    /**
     * 抽取文章内容和图片路径的方法
     * @param wmNews
     * @return
     */
    private Map parseContentAndImages(WmNews wmNews) {
        List<Map> contentList = JSON.parseArray(wmNews.getContent(), Map.class);
        //1.抽取文本内容
        String content = contentList.stream()
                .filter(map -> "text".equals(map.get("type")))
                .map(map -> String.valueOf(map.get("value")))
                .collect(Collectors.joining("_hmtt_"));
        content += "_hmtt_" + wmNews.getTitle();
        //2.抽取图片路径
        List<String> images = contentList.stream()
                .filter(map -> "image".equals(map.get("type")))
                .map(map -> String.valueOf(map.get("value")))
                .collect(Collectors.toList());
        //2.1获取封面图片
        String coverStr = wmNews.getImages();
        if (StringUtils.isNotBlank(coverStr)){
            List<String> coverImages = Arrays.stream(coverStr.split(","))
                    .map(url -> webSite + url)
                    .collect(Collectors.toList());
            images.addAll(coverImages);
        }
        //2.2整合内容图面和封面图片并去重
        images = images.stream().distinct().collect(Collectors.toList());
        //3.封装数据，返回结果
        Map result = new HashMap<>();
        result.put("content",content);
        result.put("images",images);
        return result;
    }
}
